import dbUserApi from './cloudUserApi/index';
import signActivity from './signActivity/index';
import timeCompare from './utils/timeCompare';
import moment from 'moment';
import cloud from 'wx-server-sdk';
cloud.init({
  env: 'sleep-sign-0g9xr6lm95e07431',
});
export async function main() {
  const wxContext = cloud.getWXContext();
  const log = cloud.logger();
  // 获取所有用户信息
  const { data: configs } = await dbUserApi.getConfigAll();
  const curDate = moment();
  const curDay = curDate.day() + '';
  // const curTime = curDate.toLocaleTimeString().slice(0, 5); // 08:08:08 得到时间08:08 云端 是 8:08 PM 所以不能这样
  let curTime = '' +
    (curDate.hour() < 10 ? '0' + curDate.hour() : +curDate.hour())  + ':' +
    (curDate.minute() < 10 ? '0' + curDate.minute() : +curDate.minute())
  configs.forEach(async (config) => {
    log.info({
      title: '遍历数据开始',
      name: config.name,
      // data: config,
    });
    if (!config.corn_trigger) return;
    if (!config.cookie) return;
    if (!config.name) return;
    log.info({
      title: '开始判断是否签到',
    });
    config.corn_trigger?.forEach((corn_t) => {
      log.warn({
        corn_t: corn_t.day,
        curDay: curDay,
        timelt: timeCompare.lt(curTime, corn_t.endTime),
        timegt: timeCompare.gt(curTime, corn_t.startTime),
        time: curTime,
        s_time: corn_t.startTime,
        e_time: corn_t.endTime,
      });
      const dayOk = corn_t.day == curDay
      const timeOk =
        timeCompare.lt(curTime, corn_t.endTime) &&
        timeCompare.gt(curTime, corn_t.startTime);
      if (!timeOk || !dayOk) {
        return;
      }
      log.info({
        title: '开始查询签到活动',
      });
      console.log('开始查询签到活动');
      signActivity
        .aPromise(
          corn_t.course,
          config.cookie?.uf!,
          config.cookie?._d!,
          config.cookie?._uid!,
          config.cookie?.vc3!
        )
        .then((res) => {
          log.log({
            activity: res,
            title: '开始签到',
          });
          if (typeof res == 'string') return;
          console.log('开始签到');
          signActivity
            .activityAll(config.cookie!, config.name!, res, {})
            .then((res) => {
              log.info({
                title:'签到成功'
              })
            });
        });
    });
  });
  return {
    openid: wxContext.OPENID,
    appid: wxContext.APPID,
    unionid: wxContext.UNIONID,
  };
}
main();
